//
// Created by WINDOWS on 2025/6/18.
//

#ifndef FILESPACEMONITOR_FILESPACEWATCHER_H
#define FILESPACEMONITOR_FILESPACEWATCHER_H

#ifndef FILE_SPACE_WATCHER_H
#define FILE_SPACE_WATCHER_H

#include <string>
#include <unordered_map>
#include <mutex>
#include <atomic>
#include <thread>
#include <vector>
#include <functional>
#include <chrono>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/inotify.h>
#endif

struct FileInfo {
    uint64_t size;
    std::time_t last_modified;
};

class FileSpaceWatcher {
public:
    using UpdateCallback = std::function<void(const std::string&, uint64_t)>;

    FileSpaceWatcher();
    ~FileSpaceWatcher();

    // 添加监控目录
    bool addWatch(const std::string& path, bool recursive = true);

    // 移除监控目录
    bool removeWatch(const std::string& path);

    // 获取目录总大小
    uint64_t getDirectorySize(const std::string& path);

    // 获取文件统计信息
    const std::unordered_map<std::string, FileInfo>& getFileStats() const;

    // 设置更新回调
    void setUpdateCallback(UpdateCallback callback);

    // 开始监控
    void start();

    // 停止监控
    void stop();

    // 设置大文件阈值 (字节)
    void setLargeFileThreshold(uint64_t threshold);

    // 设置频繁更新阈值 (毫秒)
    void setFrequentUpdateThreshold(int milliseconds);

private:
    void monitorThreadFunc();
    void scanDirectory(const std::string& path, bool recursive);
    void processFileEvent(const std::string& filepath);
    void handleLargeFile(const std::string& filepath);

#ifdef _WIN32
    HANDLE m_directoryHandle;
    OVERLAPPED m_overlapped;
    std::vector<BYTE> m_buffer;
    std::unordered_map<std::string, HANDLE> m_watchedDirectories;
#else
    int m_inotifyFd;
    std::unordered_map<int, std::string> m_watchDescriptors;
#endif

    std::unordered_map<std::string, FileInfo> m_fileStats;
    mutable std::mutex m_mutex;
    std::thread m_monitorThread;
    std::atomic<bool> m_running;
    UpdateCallback m_callback;
    uint64_t m_largeFileThreshold;
    int m_frequentUpdateThreshold;

    // 频繁更新的文件记录
    std::unordered_map<std::string, std::chrono::steady_clock::time_point> m_frequentFiles;
};

#endif // FILE_SPACE_WATCHER_H

#endif //FILESPACEMONITOR_FILESPACEWATCHER_H
